#include "sqlreader.h"
#include <QDataStream>
#include <QDateTime>
#include <QFile>
#include <QMessageBox>
#include <QVariant>
#include <QDebug>
#include <QXmlStreamReader>
#include <QCoreApplication>

SqlReader::SqlReader(QObject *parent)
    : QObject{parent}
{
    mDataVector = new std::vector<QByteArray*>;

    readConfigFile();
}

void SqlReader::readDBFile(QString dbFilePath)
{
    // 添加SQLite3数据库驱动
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbFilePath);

    // 打开数据库
    if (!db.open()) {
        // QMessageBox::warning(nullptr, "提示", "Error opening database: " + db.lastError().text());
        return;
    }

    // 执行查询
    QSqlQuery query;
    if (query.exec("SELECT * FROM " + dbSheetName/* + " LIMIT 1"*/)) {
        // 处理查询结果
        while (query.next()) {
            QByteArray* pData = new QByteArray;
            QDataStream stream(pData, QIODevice::WriteOnly);

            // 读取列车ID
            QString strTrainID = query.value(trainIDCol).toString();
            quint16 intTrainID = strTrainID.toUInt();
            stream << intTrainID;


            // 读取A/B系信息
            QString strSystemAB = query.value(systemABCol).toString();
            quint8 intSystem = 0;
            if(strSystemAB=="A"){
                intSystem = 1;
            }
            if(strSystemAB=="B"){
                intSystem = 2;
            }
            stream << intSystem;

            // 读取主备状态
            QString strMaster = query.value(masterCol).toString();
            quint8 intMaster = 0;
            if(strMaster == "M"){
                intMaster = 1;
            }
            if(strMaster == "S"){
                intMaster = 2;
            }
            stream << intMaster;

            // 读取CPU信息
            QString strCPU = query.value(cpuCol).toString();
            quint8 intCPU = strCPU.toUInt();
            stream << intCPU;

            // 读取周期号
            QString strCycle = query.value(cycleCol).toString();
            quint32 intCycle = strCycle.toUInt();
            stream << intCycle;

            // 读取时间
            QString strTime = query.value(timeCol).toString();

            // 单独转化年月日时分秒
            QDateTime dateTime = QDateTime::fromString(strTime, "yyyy-MM-ddThh:mm:ss");

            if (!dateTime.isValid()) {
                // QMessageBox::warning(nullptr, "提示", "the format of DateTime is invalid!");
                // qDebug()<<"the format of DateTime is invalid!";
            }

            // 转化年
            quint16 tYear = dateTime.date().year();
            stream << tYear;

            // 转化月
            quint8 tMonth = dateTime.date().month();
            stream << tMonth;

            // 转化日
            quint8 tDay = dateTime.date().day();
            stream << tDay;

            // 转化时
            quint8 tHour = dateTime.time().hour();
            stream << tHour;

            // 转化分
            quint8 tMinute = dateTime.time().minute();
            stream << tMinute;

            // 转化秒
            quint8 tSecond;
            tSecond = dateTime.time().second();
            stream << tSecond;

            // 读取变量数据
            QByteArray context = query.value(contextCol).toByteArray().remove(0,13);
            qDebug()<<context.toHex();
            *pData += context;
            mDataVector->push_back(pData);
        }
    }

    // 关闭数据库连接
    db.close();
}

void SqlReader::save(QString logFilePath)
{
    // 打开日志文件
    QFile logfile(logFilePath);
    if (!logfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(nullptr, "提示", "Failed to open the logfile: ");
    }

    // 创建一个输出文本流
    QDataStream out(&logfile);


    // 遍历每一行的Byte数据后写入文件
    for(const auto &byte : std::as_const(*mDataVector)){
        out << byte->toHex().toBase64();
    }

    qDeleteAll(mDataVector->begin(), mDataVector->end());

    delete mDataVector;
    mDataVector = nullptr;

    logfile.close();
}

void SqlReader::readConfigFile()
{
    // 将xml文件读取数据
    QFile file(QCoreApplication::applicationDirPath() + "/sqlite3.cfg");

    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug()<<"error";
    }

    QXmlStreamReader reader;

    // 指定读取设备
    reader.setDevice(&file);

    while(!reader.atEnd())
    {
        // 读取下一个标签
        reader.readNext();
        // 解析内容
        if(reader.isStartElement())
        {
            // 解析sheetName
            if(reader.name() == QString("sheetName"))
            {
                dbSheetName = reader.readElementText();
            }
            // 解析trainID
            if(reader.name() == QString("trainID"))
            {
                trainIDCol = reader.readElementText().toInt();
            }
            // 解析systemAB
            if(reader.name() == QString("systemAB"))
            {
                systemABCol = reader.readElementText().toInt();
            }
            // 解析master
            if(reader.name() == QString("master"))
            {
                masterCol = reader.readElementText().toInt();
            }
            // 解析cpu
            if(reader.name() == QString("cpu"))
            {
                cpuCol = reader.readElementText().toInt();
            }
            // 解析cycle
            if(reader.name() == QString("cycle"))
            {
                cycleCol = reader.readElementText().toInt();
            }
            // 解析time
            if(reader.name() == QString("time"))
            {
                timeCol = reader.readElementText().toInt();
            }
            // 解析context
            if(reader.name() == QString("context"))
            {
                contextCol = reader.readElementText().toInt();
            }
        }
    }

    file.close();

    return;
}
